import sqlite3

from fastapi import APIRouter, Depends
from fastapi import HTTPException
from fastapi.security import OAuth2PasswordBearer

from models import AccessKey, LoginForm

router = APIRouter()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


async def vali_token(token: str = Depends(oauth2_scheme)):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id FROM access_auth WHERE key = ?', (token,))
    access_key_id = cursor.fetchone()
    conn.close()

    if access_key_id:
        return access_key_id[0]
    else:
        raise HTTPException(status_code=403, detail="Username or Password is invalid")


@router.post("/auth/login")
async def login(request: LoginForm):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute('SELECT key FROM access_auth WHERE username = ? AND password = ? ', (request.username, request.password))
    access_token = cursor.fetchone()
    conn.close()

    if access_token:
        return {"token": access_token[0]}
    else:
        raise HTTPException(status_code=403, detail="Access key is invalid")
